<template>
  <div>
    <div class="knowledge_detail">
      <c-title :hide="false" :text="article_name || '知识库详情'">
        <router-link :to="fun.getUrl('knowledgeIndex',{},{plu: this.plugin})" slot="left">
          <span style="margin-left: 0.8rem;">主页</span>
        </router-link>
        <slot name="edit" slot="edit"><span @click="showtime(!show)">{{show?"收拢目录":"展开目录"}} </span></slot>
      </c-title>
      <div id="a_content" v-if="article" v-html="article" @click="handleHtml($event)"></div>
      <div style="margin: 0 auto;" v-if="!article">
        <van-empty description="暂无内容" />
      </div>
      <div class="score" v-if="showLove">
        <van-icon size="1.4rem" name="good-job-o" :color="articleData.is_love?'#3a75f4':''" @click="clicklove"/>
        <p class="love_count">{{love_count}}人点赞</p>
        <div class="img">
          <div v-for="(item,i) in love_member" :key="i">
            <van-image v-if="i<14" :src="item" width="1.6rem" height="1.6rem"></van-image>
          </div>
          <div v-if="love_member&&love_member.length>=14">...</div>
        </div>
      </div>
      <div class="page-up-down" v-show="article_list&&article_list.length>0">
        <div class="page-operation" :class="{'page-up':isStart}" @click="operationPage('upPage')">上一章</div>
        <div class="page-operation" :class="{'page-down':isEnd}" @click="operationPage('nextPage')">下一章</div>
      </div>
      <div class="foort" v-if="showBase" @click="showtime(true)">
        <div class="img">
          <van-image :src="base.image_url" width="5.7rem" height="3.4rem"></van-image>
        </div>
        <div class="comten">
          <div class="base_name van-ellipsis">{{base.name}}</div>
          <div class="ptag">{{base.desc}}</div>
        </div>
      </div>
      <div style="height: 1rem;"></div>
      <template v-if="isActivated">
        <van-popup v-model="show" position="left" style="height: 100%; width: 75%;">
          <div class="popup" @click="show=false">
            <van-icon style="margin-right: 10px;" name="arrow-left"/>
            <span>{{base.name}}</span>
          </div>
          <collapse :plu="plugin" :base_id="this.$route.query.base_id" :list="article_list" :catalogueProps="catalogueProps"></collapse>
        </van-popup>
      </template>

      <!-- 图片放大start -->
      <van-image-preview v-model="showBigImg" :images="bigImages" :start-position="imgStart"></van-image-preview>
      <!-- 图片放大 end -->
    </div>
    <!-- 商品列表 -->
    <c-goodsList :goods="articleData.goods"></c-goodsList>
    <!-- 商品列表 end-->
  </div>
</template>

<script>
import {  Toast, Image as VanImage } from "vant";
import cGoodsList from "@/components/goodsList";
export default {
  components: {
    collapse: () => import("./components"),
    VanImage,
    cGoodsList
  },
  data() {
    return {
      showBigImg: false,
      bigImages: [],
      imgStart: 0,
      show: false,
      articleData: {},
      article: "",
      article_name: "",
      article_list: [],
      love_count: 0,//点赞人数
      love_member: [],//点赞人头像
      base: {},//知识库信息
      isStart:true,
      isEnd:true,
      isActivated:false,

      plugin: 'message-base',//message-base商城知识库，project-template供应链知识库
      catalogueProps: {},
      showLove: true,//是否显示点赞
      showBase: true//是否显示文章模块
    };
  },
  activated() {
    this.bigImages = [];
    this.showBigImg = false;
    this.imgStart = 0;
    this.initOption();
    this.isActivated = true;
  },
  deactivated(){
    this.show = false;
    this.isActivated = false;
  },
  methods: {
    async initOption(){
      let api = new Map([
        ["message-base", {
          index: 'plugin.message-base.frontend.article.articleDetail',
          baseArticle: 'plugin.message-base.frontend.article.baseArticle',
          params: ()=>{
            return {article_id: this.$route.params.articleId, visit_source: 2}
          },
          baseArticleParams:{base_id : this.$route.query.base_id},
          showLove: true,
          showBase: true,
          list: {
            label: "article_list",
            children: "article_name",
            content: 'article'
          },
          catalogueProps: {
            label: "article_name",
            children: "child",
          },
          callback:(res)=>{},
          getUD:(list)=>{
            // 计算当前目录是否到顶（上下章）
            this.isStart = list[0]&&this.$route.params.articleId == list[0].id;
            this.isEnd = this.getIsEnd(list,this.$route.params.articleId);
          },
          nextStartPage:({type})=>{
            if(type=="upPage"){
              if(this.isStart)return this.$toast("文章已经到顶了");
              else this.upPage(this.article_list,this.article_list);
              return false;
            }
          },
          nextEndPage:({type})=>{
            if(type=="nextPage"){
              if(this.isEnd) return this.$toast("文章已经到底了");
              let articleId = this.$route.params.articleId;
              for (let i = 0; i < this.article_list.length; i++) {
                let item = this.article_list[i];
                if (item.id == articleId) {
                  if (item.child.length>=1) {
                    this.toDetail(item.child[0].id);
                    return false;
                  }else if(this.article_list[i+1]){
                    this.toDetail(this.article_list[i+1].id);
                    return false;
                  }
                  return true;
                }
                if(this.nextPage(item.child,articleId)){
                  this.toDetail(this.article_list[i+1].id);
                  return false;
                }
              }
            }
          },
        }
        ],
        ["project-template", {
          index: 'plugin.project-template.frontend.knowledge.articleDetatil',
          baseArticle: 'plugin.project-template.frontend.knowledge.knowledgeBaseCatalog',
          params: ()=>{
            return {id: this.$route.params.articleId}
          },
          baseArticleParams:{id : this.$route.query.base_id},
          showLove: false,
          showBase: false,
          list: {
            label: "knowledgeBaseArticle",
            children: "title",
            content: 'content'
          },
          catalogueProps: {
            label: "title",
            children: "has_many_yz_supply_knowledge_base_article",
          },
          callback:(res)=>{},
          getUD:()=>{
            // 计算当前目录是否到顶（上下章）
            this.isStart = this.articleData.previous_id?false:true;
            this.isEnd = this.articleData.next_id?false:true;
          },
          nextStartPage:({type})=>{
            if(type=="upPage"){
              if(!this.articleData.previous_id)return this.$toast("文章已经到顶了");
              else this.toDetail(this.articleData.previous_id);
              return false;
            }
          },
          nextEndPage:({type})=>{
            if(type=="nextPage"){
              if(!this.articleData.next_id) return this.$toast("文章已经到底了");
              this.toDetail(this.articleData.next_id);
            }
          },
        }
        ],
      ]);
      if(this.$route.query.plu) {
        this.plugin = this.$route.query.plu;
      }
      this.apiOption = api.get(this.plugin);
      this.catalogueProps = this.apiOption.catalogueProps;
      this.showLove = this.apiOption.showLove;
      this.showBase = this.apiOption.showBase;

      await this.getdata();
      this.getarticle_list();
    },
    getIsStart(list){
      // 计算是否到顶
      this.apiOption.getUD(list);
    },
    getIsEnd(list,id){
      if(list && list[list.length-1]){
        let child = list[list.length-1].child;
        if(child&&child.length>0){
          return this.getIsEnd(child,id);
        }
        return list[list.length-1].id == id;
      }
      return true;
    },
    toDetail(articleId){
      let base_id = this.$route.query.base_id;
      this.$router.push(this.fun.getUrl("knowledgeDetail", { articleId:articleId }, {base_id: base_id,plu: this.plugin}));
    },
    nextPage(list,articleId){
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (item.id == articleId) {
          if (item.child.length>=1) {
            this.toDetail(item.child[0].id);
            return false
          }else if(list[i+1]){
            this.toDetail(list[i+1].id);
            return false
          }
          return true;
        }
        if (this.nextPage(item.child,articleId)) {
          if (list[i+1]) {
            this.toDetail(list[i+1].id);
            return false;
          }else return true;
        };
      }
    },
    upPage(list,plist,pindex){
      let articleId = this.$route.params.articleId;
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (item.id == articleId) {
          let id = i<=0?plist[pindex].id:list[i-1].id;
          this.toDetail(id);
          return false;
        }
        this.upPage(item.child,list,i)
      }
    },
    operationPage(type){
      if (this.article_list&&this.article_list.length>0) {
        if(type=="upPage"){
          // 上一章
          this.apiOption.nextStartPage({type: type});
        }
        if(type=="nextPage"){
          // 下一章
          this.apiOption.nextEndPage({type: type});
        }
      }
    },
    async getdata() {
      if(this.$route.params.articleId && this.$route.params.articleId == -1) {
        this.$router.replace(this.fun.getUrl("knowledgeList", {}, { base_id: this.fun.getKey('base_id'),plu: this.plu }));
        return;
      }

      await $http.get(this.apiOption.index, this.apiOption.params(),'loading').then(res => {
        this.articleData = res.data;
        if(res.data.article) {
          try {
            this.article = decodeURIComponent(res.data.article[this.apiOption.list.content]);
          }catch (e) {
            this.article = res.data.article[this.apiOption.list.content];
          }
          this.article_name = res.data.article[this.apiOption.list.children];
          this.fun.setWXTitle(this.article_name || '知识库详情');
        }
        this.bigImages = this.getImgSrc(this.article);
        this.love_count = res.data.love_count;
        this.love_member = res.data.love_member;
        this.base = res.data.base || {};

        let goodStyle = this.$store.state.view;
        if(!goodStyle) {
          this.$store.commit("views");//重置商品列表样式
        }
      });
    },
    getarticle_list(){
      let {knowledge} = this.$store.state;
      let base_id = this.$route.query.base_id;
      if (knowledge.baseArticle&&knowledge.base_id==base_id) {
        this.article_list = knowledge.baseArticle.data[this.apiOption.list.label].filter(r => {
          return r[this.apiOption.list.children] != "";
        });
        this.getIsStart(this.article_list);
        return true;
      }
      this.showtime(false);
    },
    showtime(show) {
      if (this.article_list&&this.article_list.length>0) {
        this.show = show;
        return false;
      }
      let base_id =  this.$route.query.base_id;
      $http.get(this.apiOption.baseArticle, this.apiOption.baseArticleParams).then(res => {
        if (res.result == 1) {
          this.show = show;
          this.article_list = res.data[this.apiOption.list.label].filter(r => {
            return r[this.apiOption.list.children] != "";
          });
          this.getIsStart(this.article_list);
          this.$store.commit("setBaseArticle", {res,base_id});
        } else {
          Toast.fail("请刷新试试");
        }
      });
    },
    clicklove() {
      $http.get("plugin.message-base.frontend.article.articleLove", {
        article_id: this.$route.params.articleId,
        is_love: this.articleData.is_love ? 0 : 1
      }, "loading").then(res => {
        if (res.result == 1) {
          this.articleData.is_love = !this.articleData.is_love;
          this.articleData.is_love ? this.love_count ++ : this.love_count --;
          this.getdata();
          Toast({
            message: res.msg,
            icon: this.articleData.is_love ? "like":"like-o"
          });
        }
      });
    },
    getImgSrc(richtext) {
      let imgList = [];
      richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
        imgList.push(capture);
      });
      return imgList;
    },
    handleHtml($event) {
      let that = this;
      if ($event.target) {
        if ($event.target.nodeName == "IMG" && $event.target.parentElement.nodeName !== "A") {
          for (let i = 0; i < that.bigImages.length; i++) {
            // 编程式
            if ($event.target.currentSrc.indexOf(that.bigImages[i]) > -1) {
              that.imgStart = i;
              that.showBigImg = true;
              return;
            }
          }
        }
      }
    },
  }
};
</script>

<style lang="scss" scoped>
  .knowledge_detail {
    text-align: left;
    padding: 0 0.8rem;

    #a_content {
      background-color: #fff;
      padding: 5px;
      border-radius: 5px;
      margin-top: 5px;

      ::v-deep h2 {
        font-size: 1.5em !important;
      }

      ::v-deep h3 {
        font-size: 1.17em !important;
      }
    }

    .popup {
      border-bottom: #eee 0.05rem solid;
      padding: 10px 16px;
      display: flex;
      align-items: center;
    }

    .score {
      margin-top: 10px;
      padding: 1rem 0;
      background-color: #fff;
      border-radius: 5px;
      text-align: center;

      .love_count {
        color: #404040;
        font-weight: normal;
        font-size: 12px;
      }

      .img {
        > div {
          display: inline-block;
          border-radius: 50%;
          overflow: hidden;
          margin: 0.6rem;
        }
      }
    }

    .foort {
      margin-top: 10px;
      border-radius: 5px;
      background-color: #fff;
      display: flex;
      padding: 0.6rem 0.8rem;

      .img {
        width: 5.7rem;
        height: 3.4rem;
        padding: 0.1rem;

        img {
          width: 100%;
        }
      }

      .comten {
        flex: 1;
        padding-left: 1rem;
        word-break: break-all;
        max-width: 73%;

        .base_name {
          color: #303030;
          font-weight: bold;
          line-height: 24px;
        }

        .ptag {
          color: #838383;
          line-height: 15px;
          font-size: 11px;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 3;
          word-break: break-all;
          overflow: hidden;
        }
      }
    }

    .page-up-down {
      display: flex;
      margin-top: 10px;
      justify-content: space-around;
      .page-operation { width: 10.5rem; height: 2.625rem; text-align: center; line-height: 2.625rem; color: #3aa98b; border: #3aa98b 1px solid; border-radius: 0.2rem; }
      .page-up { color: #ccc; border: #ccc 1px solid; }
      .page-down { color: #ccc; border: #ccc 1px solid; }
    }
  }
</style>
